import 'package:audioplayers/audioplayers.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';

final CMMAudioPlayer cmmPlayer = CMMAudioPlayer();

class CMMAudioPlayer extends ChangeNotifier {
  String url; //音频链接
  String vid; //音频ID
  int curTime; //音频当前时间, 单位毫秒
  int startTime; //音频开始时间, 单位毫秒
  int maxTime; //音频总时长 ,单位毫秒
  AudioPlayerState state; //当前音频状态
  bool isPlayer = false;

  AudioPlayer _audioPlayer;

  AudioPlayer get audioPlayer => _audioPlayer;

  /// 初始化
  init() {
    _audioPlayer = AudioPlayer();
    _audioPlayer.release(); //默认模式，将在停止/完成后释放。
  }

  ///开始播放
  play(String url) async {
    if(this.url == url){
      resume();
      return;
    }
    this.url = url;
    int result = await _audioPlayer.play(url);
    if (result == 1) {
      getMaxTime();
      getCurTime();
      getCurState();
      isPlayer = true;
      notifyListeners();
    } else {
      print('音频播放错误了');
    }
  }

  setIsPlayer(bool player){
    this.isPlayer = player;
    notifyListeners();
  }

  ///暂停
  pause() {
    _audioPlayer.pause();
  }

  ///停止
  stop() {
    _audioPlayer.stop();
  }

  ///跳到固定的某个时间
  seek({int time}) {
    _audioPlayer.seek(Duration(milliseconds: curTime + time));
  }

  /// 继续播放
  resume() {
    _audioPlayer.resume();
  }

  ///获取返回时间
  getMaxTime() {
    _audioPlayer.onDurationChanged.listen((Duration d) {
      maxTime = d.inMilliseconds;
      print('总时长是${maxTime}');
      notifyListeners();
    });
  }

  ///返回当前时长
  getCurTime() {
    _audioPlayer.onAudioPositionChanged.listen((Duration p) {
      curTime = p.inMilliseconds;
      notifyListeners();
    });
  }

  /// 当前音频状态
  getCurState() {
    _audioPlayer.onPlayerStateChanged.listen((AudioPlayerState s) {
      print('当前音频状态${s}');
      state = s;
      notifyListeners();
    });
  }
}
